package com.shj.web.security;

import com.shj.model.SysMenu;
import com.shj.model.SysRoleMenu;
import com.shj.service.SysPowerService;
import com.shj.service.SysRolePowerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description TODO 自定义权限资源过滤器，实现动态权限认证
 * 主要责任是当访问一个urlⅩ，返回这个url需要的权限
 * @Author songhuajian
 * @Date 2020/3/13 14:37
 **/
@Component
@Slf4j
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Resource
    private SysPowerService sysPowerService;
    @Resource
    private SysRolePowerService sysRolePowerService;

    /**
     * @description 返回本次访问需要的权限
     * @author songhuajian
     * @date 2020/3/13 14:40
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取请求的路径
        String url = ((FilterInvocation) object).getRequestUrl();
        // 正则匹配？之前的真实url
        String pattern = ".*(?=\\?)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(url);
        if (m.find()) {
            url = m.group(0);
        }
        log.info(url);
        //根据请求路径和方式查询权限ID
        SysMenu sysMenu = sysPowerService.findByUrl(url);
        //根据权限ID查询角色ID
        List<SysRoleMenu> rolePowerList = new ArrayList<>();
        if (sysMenu != null){
            rolePowerList = sysRolePowerService.findByMenuId(sysMenu.getMenuId());
        }

        int size = rolePowerList.size();
        if (size > 0){
            String[] values = new String[size];
            for (int i=0;i<size;i++){
                values[i] = rolePowerList.get(i).getRoleId();
            }
            return SecurityConfig.createList(values);
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
